package top.jlzhou.key.service.impl;

import top.jlzhou.key.entity.Reg;
import top.jlzhou.key.mapper.RegMapper;
import top.jlzhou.key.mapper.SoftMapper;
import top.jlzhou.key.service.RegService;
import top.jlzhou.tools.CDKey;
import top.jlzhou.T;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import java.time.LocalDateTime;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * <p>
 * 注册码信息 服务实现类
 * </p>
 *
 * @author J.L.Zhou
 * @since 2018-10-07
 */
@Service
public class RegServiceImpl extends ServiceImpl<RegMapper, Reg> implements RegService {

	@Autowired
	private T tools;

	@Autowired
	private SoftMapper softMapper;

	@Override
	@Transactional
	public void reg(Reg reg) throws Exception {

		try {
			CDKey.getMac(reg.getRegMac());
		} catch (Exception ex) {
			throw new Exception("客户端信息错误！", ex);
		}

		try {
			if (softMapper.selectById(reg.getSoftId()) == null) {
				throw new Exception("未知的软件编号：" + reg.getSoftId());
			}
		} catch (Exception ex) {
			throw new Exception("获取软件信息失败", ex);
		}
		
		

		if ( exists(reg.getRegTel(), reg.getSoftId())) {
			throw new Exception("该手机号码已经注册过该软件了");
		}
		
		try {
			reg.setRegNum(CDKey.get(reg.getRegTel(), reg.getSoftId(), reg.getRegMac()));

		} catch (Exception ex) {
			throw new Exception("生成序列号失败", ex);
		}

		reg.setLocked(false);
		reg.setRegTime(LocalDateTime.now());

		baseMapper.insert(reg);
	}

	@Override
	public boolean exists(String tel, Integer id) {
		Reg r = baseMapper.selectOne(
				new QueryWrapper<Reg>().eq("soft_id", id).and(i -> i.eq("reg_tel", tel)));
		return r!=null;
	}
}
